package ts

import (
	"fmt"
	"gitee.com/xiaochengtech/unified-structure/src/common"
	"gitee.com/xiaochengtech/unified-structure/src/util"
	"sort"
	"strings"
)

// 处理模型文件
func modelFile(ctx common.Context) (result []string) {
	lines := make([]string, 0)
	// 整理Extend字段的附加import
	referItems := make(map[string][]string)
	extendItems := make([]string, 0)
	for _, item := range ctx.File.List {
		if util.IsExtend(item.Type) {
			referItems[item.GetRefFile()] = append(referItems[item.GetRefFile()], item.GetRefName())
			extendItems = append(extendItems, item.GetRefName())
		}
	}
	// 生成文件
	if len(extendItems) > 0 {
		lines = append(lines, fmt.Sprintf("export interface %s extends %s {", ctx.File.Name, strings.Join(extendItems, ", ")))
	} else {
		lines = append(lines, fmt.Sprintf("export interface %s {", ctx.File.Name))
	}
	for _, item := range ctx.File.List {
		if util.IsExtend(item.Type) {
			continue
		}
		ctx.Field = item
		varLines, needRefer := modelItem(ctx)
		if len(varLines) == 0 {
			continue
		}
		for _, varLine := range varLines {
			lines = append(lines, util.TabStop(varLine, 1))
		}
		if needRefer {
			referItems[item.GetRefFile()] = append(referItems[item.GetRefFile()], item.GetRefName())
		}
	}
	lines = append(lines, fmt.Sprintf("}"))
	// 获取有序的refer_line
	keys := make([]string, 0)
	for fileName, _ := range referItems {
		keys = append(keys, fileName)
	}
	sort.Strings(keys)
	referLines := make([]string, 0)
	for _, fileName := range keys {
		referNames := referItems[fileName]
		referLines = append(referLines, fmt.Sprintf("import { %s } from './%s';", strings.Join(referNames, ", "), fileName))
	}
	// 拼接
	if len(referLines) > 0 {
		result = append(result, referLines...)
		result = append(result, "")
	}
	result = append(result, lines...)
	return
}
